﻿using System;
using System.Collections.Generic;
using G.Runtime;
using GameRuntimeControls;

namespace Conquest
{
    public partial class CityStateView : GameView
    {
        public CityStateView()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();
            
            base.SpaceChanged += delegate(GameSpace space) 
            {
                space.Elements.ElementAddedEvent += delegate(GameElement subject) 
                {  
                    GamePlayer winner = FindWinner(subject.Game);
                    if (winner != null)
                    {
                        base.SquareColor = winner.Color;
                    }
                };
            };
            
        }
        
        private GamePlayer FindWinner(GameSpace space)
        {
            GamePlayer result = null;
            int highestCount = 0;
            
            Dictionary<string, int> data = new Dictionary<string, int>();
            foreach (GameElement element in space.Elements) 
            {
                
                if (element.Player == null || element.Player == "") 
                {
                    continue;
                }
                
                if (!data.ContainsKey(element.Player)) 
                {
                    data.Add(element.Player, 1);
                    if (highestCount == 0)
                    {
                        highestCount = 1;
                        GamePlayer player = space.Players[element.Player];
                        result = player;
                    }
                }
                else 
                {
                    int count = data[element.Player];
                    count++;
                    data[element.Player] = count;
                    if (count > highestCount)
                    {
                        highestCount = count;
                        GamePlayer player = space.Players[element.Player];
                        result = player;
                    }
                }
            }
            
            return result;
        }
        
    }
}
